# -*- coding: utf-8 -*-
# 定义登录接口
import pymysql
from cursor import cursor
from flask import request, jsonify, Blueprint, render_template

from project import config

# 创建数据库连接和游标对象
db = pymysql.connect(host=config.BaseConfig.HOSTNAME, port=config.BaseConfig.PORT, user=config.BaseConfig.USERNAME,
                     password=config.BaseConfig.PASSWORD, database=config.BaseConfig.DATABASE)
cursor = db.cursor()

bp = Blueprint("user", __name__, url_prefix="/user")


@bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data['username']
    password = data['password']

    # 查询数据库验证用户信息
    cursor.execute('SELECT * FROM user WHERE (username=%s OR email=%s OR phone=%s) AND password=%s',
                   (username, username, username, password))
    user = cursor.fetchone()

    if user:
        user_dict = {
            'id': user[0],
            'username': user[1],
            'email': user[2],
            'phone': user[3]
            # 添加其他字段...
        }
        print("登录信息:")
        print(user_dict)
        return jsonify({'code': 200, 'msg': '登录成功!', 'data': user_dict})
    else:
        return jsonify({'code': 400, 'msg': '账号或密码错误!'})


@bp.route('/loginPage', methods=['GET'])
def loginPage():
    return render_template('login.html')


@bp.route('/register', methods=['POST'])
def register():
    print("运行注册")
    data = request.get_json()
    username = data['username']
    email = data['email']
    phone = data['phone']
    password = data['password']

    # 查询数据库是否存在该用户信息
    cursor.execute('SELECT * FROM user WHERE username = %s OR email = %s OR phone = %s', (username, email, phone))
    user1 = cursor.fetchone()
    if user1 :
        return jsonify({'code': 201, 'msg': '账号已存在!'})
    else:
        # 查询数据库验证用户信息
        cursor.execute('insert into user(username, email, phone, password) values (%s, %s, %s, %s)',
                       (username, email, phone, password))
        db.commit()

        # 查询数据库验证用户信息
        cursor.execute('SELECT * FROM user WHERE username = %s', username)
        user = cursor.fetchone()

        if user:
            user_dict = {
                'id': user[0],
                'username': user[1],
                'email': user[2],
                'phone': user[3]
                # 添加其他字段...
            }
            print("注册的信息:")
            print(user_dict)
            return jsonify({'code': 200, 'msg': '注册成功!', 'data': user_dict})
        else:
            return jsonify({'code': 400, 'msg': '注册失败!'})




@bp.route('/registerPage', methods=['GET'])
def registerPage():
    return render_template('register.html')


@bp.route('/changePassPage', methods=['GET'])
def changePassPage():
    return render_template('changePass.html')
